// src/store/reducers/auth.reducer.ts
import { AuthUnionType, RESET_SIGNUP, SIGNIN, SIGNIN_FAIL, SIGNIN_SUCCESS, SIGNUP, SIGN_FAIL, SIGN_SUCCESS } from "../actions/auth.action";

export interface AuthState {
    signup: {
        loaded: boolean, 
        success: boolean,
        message: string
    },
    signin: {
        loaded: boolean,
        success: boolean,
        message: string
    }
}

// 初始化 auth 状态
const initialState: AuthState = {
    signup: {
        loaded: false,  // 是否请求完成
        success: false, // 是否注册成功
        message: ''     // 错误信息
    },
    signin: {
        loaded: false,
        success: false,
        message: ''
    }
}

export default function authReducer(
    state = initialState,
    action: AuthUnionType
) {
    switch (action.type) {
        // 发起注册请求
        case SIGNUP:
            return {
                ...state,
                signup: {
                    loaded: false,
                    success: false
                }
            }
        // 注册成功
        case SIGN_SUCCESS:
            return {
                ...state,
                signup: {
                    loaded: true,
                    success: true
                }
            }
        // 注册失败
        case SIGN_FAIL:
            return {
                ...state,
                signup: {
                    loaded: true,
                    success: false,
                    message: action.message
                }
            }
        case RESET_SIGNUP:
            return {
                ...state,
                signup: {
                    loaded: false, 
                    success: false,
                    message: ''
                }
            }
        case SIGNIN:
            return {
                ...state,
                signin: {
                    loaded: false,
                    success: false,
                    message: ''
                }
            }
        case SIGNIN_SUCCESS:
            return {
                ...state,
                signin: {
                    loaded: true,
                    success: true,
                    message: ''
                }
            }
        case SIGNIN_FAIL:
            return {
                ...state,
                signin: {
                    loaded: true,
                    success: false,
                    message: action.message
                }
            }
        default:
            return state
    }
}